import { Injectable } from '@nestjs/common';
import { CreateWeaponDto } from './dto/create-weapon.dto';
import { UpdateWeaponDto } from './dto/update-weapon.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Weapon } from './entities/weapon.entity';
import { Repository } from 'typeorm';
import { PageQuery } from '../../../util/entity/page.entity';
import { buildQuery } from '../../../util/common-fn';
import { FileService } from '../../common/file/file.service';

@Injectable()
export class WeaponService {
  constructor(
    @InjectRepository(Weapon)
    private weaponRepository: Repository<Weapon>,
    private fileService: FileService,
  ) {}
  async create(createWeaponDto: CreateWeaponDto) {
    await this.weaponRepository.save(createWeaponDto);
    await this.fileService.setUsed(createWeaponDto.imageUrl);
    return true;
  }

  findAll(pageQuery: PageQuery<Weapon>) {
    return this.weaponRepository.findAndCount(buildQuery(pageQuery));
  }

  findOne(id: number) {
    return this.weaponRepository.findOneByOrFail({ id });
  }

  async update(id: number, updateWeaponDto: UpdateWeaponDto) {
    await this.weaponRepository.update({ id }, updateWeaponDto);
    await this.fileService.setUsed(updateWeaponDto.imageUrl);
    return true;
  }

  remove(id: number) {
    return this.weaponRepository.softDelete({ id });
  }
}
